@echo off
cd /d "%~dp0"

:: Set color - green text
color 0A

echo ========================================
echo   Star Resonance DPS Counter
echo    Simplified One-Click Launcher
echo ========================================
echo [INFO] Fast startup with automatic cleanup
echo.

:: Basic checks
echo [CHECK] Checking basic environment...

:: Check Node.js
node --version >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Node.js not found!
    echo [TIPS] Please install Node.js first: https://nodejs.org/
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

for /f "tokens=*" %%i in ('node --version') do (
    echo [SUCCESS] Node.js: %%i
)

:: Check project files
if not exist "server.js" (
    echo [ERROR] server.js file does not exist!
    echo [TIPS] Please ensure you run this script in the project root directory
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

if not exist "node_modules" (
    echo [ERROR] Dependencies not installed!
    echo [TIPS] Please run install.bat first to install dependencies
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

echo [SUCCESS] Basic environment check completed

:: Automatic process cleanup
echo [CLEANUP] Automatic process cleanup in progress...

:: Clean all Node.js and Electron processes
echo [INFO] Terminating existing processes...
taskkill /f /im node.exe >nul 2>&1
taskkill /f /im electron.exe >nul 2>&1

:: Clean port 8989 specifically
for /f "tokens=5" %%i in ('netstat -ano ^| find ":8989" ^| find "LISTENING"') do (
    taskkill /f /pid %%i >nul 2>&1
)

:: Use WMIC for stubborn processes
wmic process where "name='node.exe'" delete >nul 2>&1

:: Wait for cleanup
timeout /t 3 >nul

echo [SUCCESS] Cleanup completed, ready to start

:: Create auto input configuration
echo [PREPARE] Creating auto configuration...

:: Delete old config file to avoid format issues
if exist server_input.txt del server_input.txt >nul 2>&1

:: Use standard method to create config file
(
echo 3
echo info
) > server_input.txt

:: Verify config file
if exist server_input.txt (
    echo [SUCCESS] Config file created
    echo [DEBUG] Config content:
    type server_input.txt
) else (
    echo [ERROR] Config file creation failed!
)

echo.
echo ========================================
echo         Starting Service
echo ========================================
echo.

:: Start server
echo [START] Starting server...
echo [INFO] Using auto configuration: device 3, log level info
echo.

:: Simple and direct startup method
start /b cmd /c "node server_wrapper.js > server_output.log 2>&1"

:: Wait for startup
echo [WAIT] Waiting for server startup...
set /a counter=0
:wait_loop
timeout /t 3 >nul
set /a counter+=1

:: Check port
netstat -an | find ":8989" | find "LISTENING" >nul 2>&1
if %errorLevel% equ 0 (
    echo [SUCCESS] Server started successfully!
    goto start_browser
)

:: Check log file
if exist server_output.log (
    findstr /C:"Web Server started" server_output.log >nul 2>&1
    if %errorLevel% equ 0 (
        echo [SUCCESS] Server started successfully!
        goto start_browser
    )
    
    findstr /C:"ERROR Error error" server_output.log >nul 2>&1
    if %errorLevel% equ 0 (
        echo [ERROR] Startup error detected!
        echo ============== Error Information ==============
        type server_output.log
        echo ============== End Error Information ==============
        goto error_exit
    )
)

if %counter% lss 15 (
    echo [WAIT] Waiting... [%counter%/15]
    goto wait_loop
) else (
    echo [ERROR] Startup timeout!
    goto error_exit
)

:start_browser
echo.
echo [START] Opening browser...
start http://localhost:8989

echo.
echo ========================================
echo          Startup Complete!
echo ========================================
echo.
echo Browser: http://localhost:8989
echo.
echo [INFO] Server is running in background
echo [INFO] Closing this window will stop the server
echo [INFO] Press Ctrl+C to stop service
echo.
echo Monitoring service status...

:: Simple monitoring loop with overlay status
:monitor
timeout /t 30 >nul

:: 检查服务器状态
netstat -an | find ":8989" | find "LISTENING" >nul 2>&1
if %errorLevel% equ 0 (
    set "SERVER_STATUS=正常"
) else (
    set "SERVER_STATUS=停止"
)

echo [%time%] 服务运行状态 - 浏览器: http://localhost:8989 (服务器: %SERVER_STATUS%)
echo [提示] 如需浮动覆盖层，请运行完整版 "一键启动.bat"

goto monitor

:error_exit
echo.
echo [ERROR] Startup failed!
echo.
echo [SOLUTIONS] Please try the following solutions:
echo   1. Run as administrator
echo   2. Check firewall settings
echo   3. Restart computer and try again
echo   4. Check if port 8989 is occupied
echo.
if exist server_output.log (
    echo [DEBUG] Server output log:
    echo ================================
    type server_output.log
    echo ================================
)
echo.
echo Press any key to exit...
pause >nul
exit /b 1
